import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Select, Modal, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import debounce  from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import UserNoticeDialog from './components/UserNoticeDialog';
import AddUserForm from './components/AddUserForm';
import ParentOrgListComponent from './components/ParentOrgListComponent';
import RoleListComponent from './components/RoleListComponent';
import { UserListItem } from './data.d';
import { userList, addUser, updateUser, userRemove, updateState } from './service';

const { Search } = Input;
const { Option } = Select;

const UserList: React.FC<{}> = () => {
  const [noticeVisible, handleNoticeVisible] = useState<boolean>(false);
  const [userModalVisible, handleModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<UserListItem>({});
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<UserListItem[]>([]);
  const [disabled, handleDisabled] = useState<boolean>(true);//所属角色是否可用，根据所属机构
  const [orgId, setOrgId] = useState<number>(10000);//【所属角色】与【所属机构】联动

  //添加用户
  const addUserComment = (user: UserListItem) => {
    new Promise((resolve, reject) => {
      addUser(user)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              const hide = message.success('添加成功');
              setSelectedRows([]);
              handleModalVisible(false);
              if (actionRef.current) {
                hide();
                actionRef.current.reload();
              }
              resolve(true);
            } else {
              message.error('添加失败，'+res.message);
              resolve(false);
            }
          }else {
            message.error('添加失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('添加失败');
          reject(error);
        });
    });
  };

  //编辑用户
  const updateUserComment = (user: UserListItem) => {
    new Promise((resolve, reject) => {
      updateUser(user)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              const hide = message.success('保存成功');
              setSelectedRows([]);
              handleModalVisible(false);
              if (actionRef.current) {
                hide();
                actionRef.current.reload();
              }
              resolve(true);
            }else {
              message.error('保存失败，'+res.message);
              resolve(false);
            }
          }else {
            message.error('保存失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('保存失败');
          reject(error);
        });
    });
  };

  //用户启用停用弹出框
  const updateStateCommand = (record: UserListItem) => {
    if (record != null && record != undefined) {
      let id = record.id;
      let userState = record.userState;
      let title = "";
      if(userState == 'ENABLE'){
        title = "停用";
      }else{
        title = "启用";
      }
      Modal.confirm({
        visible: deleteModalVisible,
        title: '是否'+title,
        icon: <QuestionCircleOutlined />,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise((resolve, reject) => {
            updateState(id)
              .then((res) => {
                if (res.code === 200) {
                  const hide = message.success(title+'成功');
                  handleDeleteModalVisible(false);
                  if (selectedRowsState.length > 0) {
                    let id_list = id.toString().split(',');
                    for (var i in selectedRowsState) {
                      for (var j in id_list) {
                        if (selectedRowsState[i].id == id_list[j]) {
                          selectedRowsState.splice(i, 1);
                        }
                      }
                    }
                  }
                  hide();
                  if (selectedRowsState.length == 0) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  } else {
                    actionRef.current?.reload?.();
                  }
                  resolve(true);
                } else {
                  message.error(title+'失败');
                  resolve(false);
                }
              })
              .catch((error) => {
                message.error(title+'失败');
                reject(error);
              });
          });
        },
      });
    }
  };

  //用户删除--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此用户将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          userRemove(id)
            .then((res) => {
              if (res.code === 200) {
                const hide = message.success('删除成功');
                handleDeleteModalVisible(false);
                if (selectedRowsState.length > 0) {
                  let id_list = id.toString().split(',');
                  for (var i in selectedRowsState) {
                    for (var j in id_list) {
                      if (selectedRowsState[i].id == id_list[j]) {
                        selectedRowsState.splice(i, 1);
                      }
                    }
                  }
                }
                hide();
                if (selectedRowsState.length == 0) {
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                } else {
                  actionRef.current?.reload?.();
                }
                resolve(true);
              } else {
                message.error('删除失败');
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };
  //【新建/编辑】对话框，确定按钮点击
  const handleUpdate = async (values: UserListItem) => {
    if (values != null && values != undefined) {
      if (values.id != undefined) {
        //编辑用户
        if(values.password == values.original_password){
          values.password = undefined;
          values.original_password = undefined;
        }
        updateUserComment(values);
      } else {
        //添加用户
        values.original_password = undefined;
        addUserComment(values);
      }
    }
  };

  //重置监听
  const onReset = () =>{
    handleDisabled(true);
  }

  const columns: ProColumns<UserListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true,
      width:80,
    },
    {
      title: '用户名',
      dataIndex: 'nickname',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入用户名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
      ellipsis:true,
      width:100,
    },
    {
      title: '所属机构',
      dataIndex: 'orgId',
      hideInForm: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <ParentOrgListComponent 
              defaultvalue={-1}
              type="orgId"
              selectChange={(value) => {
                form.setFieldsValue({"orgId": value,"roleId":null});
                if(value){
                  setOrgId(value);
                  handleDisabled(false);
                }else{
                  handleDisabled(true);
                }
                form.submit();
              }}
              >
            </ParentOrgListComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable:true,
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'orgName',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '所属角色',
      dataIndex: 'roleId',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        const value="";
        if (status !== 'open') {
          return (
            <RoleListComponent 
              defaultValue={null}
              value={value} 
              disabled={disabled}
              selector={orgId}
              selectChange={(value) => {
                form.setFieldsValue({roleId:value});
                form.submit();
              }}>
            </RoleListComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable:true,
      valueType: 'text',
    },
    {
      title: '所属角色',
      dataIndex: 'roleName',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '状态',
      dataIndex: 'userState',
      width:100,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select 
              defaultValue=""
              showSearch
              optionFilterProp="children"
              style={{ width: 200 }} 
              onChange={(value) => form.submit()}
              >
              <Option value="">所有</Option>
              <Option value="ENABLE">启用</Option>
              <Option value="DISABLE">停用</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        ENABLE: { text: '已启用', status: 'Success' },
        DISABLE: { text: '已停用', status: 'Error' },
      },
    },
    {
      title: '真实姓名',
      dataIndex: 'username',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      hideInSearch: true, 
    },
    {
      title: '用户类型',
      dataIndex: 'scope',
      valueType: 'text',
      hideInSearch: true, 
      render: (scope,record) => (
        scope=="SYSTEM"?<Tag color="#f50">SYSTEM</Tag>: 
        record.id == JSON.parse(localStorage.getItem("user")).userId?<Tag color="#108ee9">CURRENT</Tag>:""
      )
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
         <a
            onClick={() => {
              handleNoticeVisible(true);
              setFormValues(record);
            }}
          >
            通知
          </a>
          <Divider type="vertical" />
          <a style={{color:
          ((record.scope == "SYSTEM" && 
          JSON.parse(localStorage.getItem("user")).orgId != 10000)||
          (record.id == JSON.parse(localStorage.getItem("user")).userId))?undefined:
            (record.userState == 'ENABLE' ? "#ff4d4f" : "#1890ff")}}
            disabled={
              ((record.scope == "SYSTEM" && 
                JSON.parse(localStorage.getItem("user")).orgId != 10000)||
                (record.id == JSON.parse(localStorage.getItem("user")).userId))?true:false //条件：1.当前登录非root用户，系统用户不能删除。
            }
            onClick={() => {
              updateStateCommand(record);
            }}
          >
            {record.userState == 'ENABLE' ? "停用" : "启用"}
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            disabled={
              ((record.scope == "SYSTEM" && 
                JSON.parse(localStorage.getItem("user")).orgId != 10000) ||
                (record.id == JSON.parse(localStorage.getItem("user")).userId))?true:false //条件：1.当前登录非root用户，系统用户不能删除。2.当前用户不能删除自己
            }
            onClick={() => {
              delConfirm(record.id);
            }}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<UserListItem>
        options={false}
        onReset={onReset}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }} //默认每页显示10条
        toolBarRender={() => [
          <Button type="primary" onClick={() => {handleModalVisible(true);setFormValues("");}}>
            <PlusOutlined /> 新建用户
          </Button>,
        ]}
       request={(params, sorter, filter) => userList(params, sorter, filter)}
        columns={columns}
      />
      <UserNoticeDialog
        onCancel={() => handleNoticeVisible(false)} 
        onSubmit={()=>{
          handleNoticeVisible(false);
          actionRef.current?.reload?.();
        }}
        modalVisible={noticeVisible}
        id={formValues.id}
        >
      </UserNoticeDialog>
      <AddUserForm 
        onSubmit={handleUpdate}
        onCancel={() => handleModalVisible(false)} 
        modalVisible={userModalVisible}
        values={formValues}
        >
        <ProTable<UserListItem, UserListItem>
        />
      </AddUserForm>
    </PageContainer>
  );
};

export default UserList;
